# coding: utf8
from tornado import gen

from app.base_controller import BaseController
from app.models import Goods, GoodsComment
from libs.util import check_param


# /api/goods-list
class GoodList(BaseController):
    @gen.coroutine
    def get(self):

        vo = Goods.objects.filter(state=0). \
            prefetch_related('price'). \
            prefetch_related('banner')
        order = self.get_argument("order", '')
        if order and 'sales' in order:
            vo = vo.order_by(order)
        elif 'price' in order:
            _list = [key.to_dict(photo_style='/350_320') for key in vo.all()]
            if order == 'price':
                _list.sort(key=lambda k: (k.get('price').get('transaction_price')))
            if order == '-price':
                _list.sort(key=lambda k: (-k.get('price').get('transaction_price')))
            paginator = self.pagination_list(object_list=_list, page_num=int(self.get_argument("pageNum", 1)))
            return self.render_json(data=paginator)
        else:
            vo = vo.order_by('show_order', '-update_time')

        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
        return self.render_json(data=paginator)


# /api/goods-top
class GoodTop(BaseController):
    @gen.coroutine
    def get(self):
        vo = Goods.objects.filter(state=0). \
            prefetch_related('price'). \
            prefetch_related('banner')
        vo = vo.order_by('show_order', '-update_time')
        paginator = self.pagination(vo.all(), number_per_page=4, page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
        return self.render_json(data=paginator)


# /api/goods-detail
class GoodDetail(BaseController):
    @gen.coroutine
    def get(self):
        id = self.get_argument("id", 1)

        vo = Goods.objects.filter(id=id). \
            prefetch_related('price'). \
            prefetch_related('banner').first()
        return self.render_json(data=vo.to_dict(type=2, photo_style='/350_320'))


# /goods-comment
class CommentList(BaseController):
    @gen.coroutine
    def get(self):
        goods_id = self.get_argument("goods_id")
        param = [goods_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = GoodsComment.objects.filter(state=0).filter(goods_id=goods_id). \
            select_related('price'). \
            select_related('user').order_by("-create_time")
        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
        return self.render_json(data=paginator)
